<template>
  <div>
    <!-- 添加按钮 -->
    <!-- <el-button type="primary"
               icon="el-icon-plus"
               style="margin: 10px 0"
               @click="showDialog">添加</el-button> -->
    <!-- <el-form ref="searchForm"
             :model="search"
             label-width="80px">
      <el-form-item label="通过标题搜索" prop="content">
        <el-input v-model="search.content"
                  placeholder="请输入标题"></el-input>
        <el-button type="primary"
                   @click="Search">搜索</el-button>
      </el-form-item>
    </el-form> -->

    <!-- 品牌表格 -->
    <!-- 
    data  显示的数据
    prop	对应列内容的字段名，也可以使用 property 属性
    type:index 通过给 type=index 的列传入 index 属性，可以自定义索引  
    slot-scope  用于给插槽定义作用域
    label   显示的标题
   -->
    <el-table style="width: 100%"
              border
              :data="list">
      <el-table-column prop="id"
                       label="序号"
                       width="80px"
                       align="center">
      </el-table-column>
      <el-table-column prop="title"
                       width="80px"
                       label="标题"></el-table-column>
      <el-table-column prop="content"
                       label="内容"></el-table-column>
      <el-table-column prop="viewed"
                       width="80px"
                       label="浏览数"></el-table-column>
      <el-table-column prop="thumb"
                       width="80px"
                       label="点赞数"></el-table-column>
      <el-table-column prop="cover"
                       label="封面">
        <template slot-scope="{ row, $index }">
          <img v-for="c in row.cover.split(',')"
               :key="c.id"
               :src="c"
               alt=""
               style="width: 100px;margin-right:10px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop"
                       label="操作">
        <template slot-scope="{ row, $index }">
          <el-button type="warning"
                     icon="el-icon-edit"
                     @click="updateUser(row)">修改</el-button>
          <el-button type="primary"
                     icon="el-icon-delete"
                     @click="deleteUser(row)"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <!-- 
    layout 组件布局，子组件名用逗号分隔
    current-page	当前页数，支持 .sync 修饰符
    page-sizes	每页显示个数选择器的选项设置
    page-size	每页显示条目个数，支持 .sync 修饰符
    total	总条目数
   -->
    <el-pagination style="margin-top: 20px; text-align: center"
                   layout="prev, pager, next, jumper, ->,sizes,total"
                   :current-page="page"
                   :page-size="limit"
                   @size-change="handleSizeChange"
                   @current-change="getPageList"
                   :page-sizes="[3, 5, 10]"
                   :total="total">
    </el-pagination>
    <!-- 添加用户对话框 -->
    <el-dialog title="编辑用户"
               :visible.sync="dialogVisible"
               width="30%">
      <!-- 用户名称 -->
      <el-form style="width: 100%"
               :model="tmForm"
               ref="ruleform">
        <el-form-item label="标题"
                      prop="title">
          <el-input v-model="tmForm.title"></el-input>
        </el-form-item>
        <el-form-item label="viewed"
                      prop="email">
          <el-input-number v-model="tmForm.viewed"
                           :min="0"
                           :max="9999"></el-input-number>
        </el-form-item>
        <el-form-item label="点赞数"
                      prop="thumb">
          <el-input-number v-model="tmForm.thumb"
                           :min="0"
                           :max="9999"></el-input-number>

        </el-form-item>
        <el-form-item label="内容"
                      prop="content">
          <el-input type="textarea"
                    autosize
                    v-model="tmForm.content"></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo"
                      prop="avatar_url">
          <el-upload class="avatar-uploader"
                     :limit='3'
                     list-type="picture-card"
                     action="/user/upload_img"
                     :on-exceed="handleExceed"
                     :on-remove="handleCoverRemove"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <!-- <img v-for="c in tmForm.cover.split(',').slice(0,tmForm.cover.split(',').length-1)"
                 :key="c.id"
                 :src="c"
                 class="avatar" /> -->
            <div slot="tip"
                 class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
          <el-dialog :visible.sync="UpdialogVisible">
            <img width="100%"
                 :src="UpdialogImageUrl"
                 alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="Cancel">取 消</el-button>
        <el-button type="primary"
                   @click="AddOrUpdateTradeMark">添 加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
const validatePhone = (rule, value, callback) => {
  // 定义一个正则来验证手机号是否是有效的
  const phoneReg = /^0?(13|14|15|18|17)[0-9]{9}$/;
  if (phoneReg.test(value)) {
    return callback();
  }
  return callback(new Error("请输入有效的手机号"));
};
const validateEmail = (rule, value, callback) => {
  // 定义一个正则来验证邮箱是否是有效的
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (emailReg.test(value)) {
    return callback();
  }
  return callback(new Error("请输入有效的邮箱"));
};
export default {
  name: "Article",
  props: {

  },
  components: {

  },
  data () {
    return {
      // 分页器当前页数
      page: 1,
      // 当前页数展示条目
      limit: 10,
      // 总共数据条数
      total: 0,
      UpdialogVisible: false,
      UpdialogImageUrl: "",
      // 商品列表信息
      list: [],
      viewlist: [],
      search: {
        content: ''
      },
      // 是否显示对话框
      dialogVisible: false,
      // 存储原本的封面图
      originUrl: "",
      // 对话框数据
      tmForm: {
        title: "",
        content: "",
        viewed: 0,
        thumb: 0,
        cover: ""
      },
      // 对话框表单校验
      rules: {
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' },
        ],
        nick_name: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' },
        ],
        phone: [{ validator: validatePhone, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }],
        avatar_url: [
          { required: false, message: '请选择用户头像' }
        ]
      }
    };
  },
  computed: {

  },
  watch: {
  },
  created () {

  },
  mounted () {
    // 在切换到页面时发送请求获得品牌信息
    this.getPageList()
    this.handleSizeChange(this.limit)
  },
  methods: {
    // 获取品牌接口功能
    async getPageList (pager = 1) {
      this.page = pager;
      console.log('aa');

      const { page, limit } = this
      const { data: res } = await this.$API.article.getArticleList('all')
      console.log(res);
      this.total = res.length
      this.viewlist = res
      let cnum = (page - 1) * this.list.length
      this.list = res.slice(cnum, limit + cnum)
    },
    // 切换每页最大显示商品数目功能
    handleSizeChange (limit) {
      this.limit = limit;
      // 重新发送请求
      // this.getPageList()
      let cnum = (this.pnum - 1) * this.viewlist.length
      this.list = this.list.slice(cnum, this.psize + cnum)
    },
    // 显示添加品牌对话看
    showDialog () {
      this.dialogVisible = true
      // 初始化对话框数据
      this.tmForm = {}
    },
    // 上传图像成功回调
    handleAvatarSuccess (res, file) {
      console.log(res);
      // 收集品牌图片数据
      this.tmForm.cover += res.data.url + ","
    },
    // 上传前回调
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 更新或添加品牌功能
    async AddOrUpdateTradeMark () {
      this.dialogVisible = false;
      if (!this.tmForm.cover) this.tmForm.cover = this.originUrl
      // 发起请求
      let result = await this.$API.article.updateArticle(this.$qs.stringify(this.tmForm))
      console.log(result);
      // 如果请求成功
      if (result.status === 200) {
        // 判断是添加还是更新
        this.$message({
          type: "success",
          message: "修改成功"
        })
        // 再次发起请求获得数据,判断点击的是修改还是添加
        this.getPageList(this.tmForm.id ? this.page : 1)      }
    },
    Cancel () {
      this.dialogVisible = false
      this.tmForm = {}
    },
    // 修改品牌功能
    updateUser (row) {
      this.dialogVisible = true;
      // if (row.cover)
      //   row.cover = row.cover.slice(0, row.cover.length)
      console.log(row);
      // 浅拷贝当前页数据,点击取消不上传到服务器
      this.tmForm = { ...row }
      this.tmForm.cover = ""
      this.originUrl = row.cover //备份
    },
    deleteUser (row) {
      this.$confirm(`是否删除${row.name}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发送删除请求
        const result = await this.$API.article.deleteArticle(row.id)
        if (result.status == 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 如果是一页就返回当前页如果不是则返回
          this.getPageList(this.list.length > 1 ? this.page : this.page - 1)
        }
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleCoverRemove (file, fileList) {
      console.log(file, fileList);
      var that = this
      let relist = that.tmForm.cover.split(',').filter(item => {
        return item != file.response.data.url && item
      })
      console.log('filter', relist);
      that.tmForm.cover = ""
      relist.forEach(item => {
        that.tmForm.cover += item + ","
      })
    },
    handleExceed () {
      this.$message.error("超出上传上限")
    }
  }

};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-input {
  width: 80%;
}
</style>
